<?php

namespace Phone\Model;

use Think\Model;

class ConfigDeliveryModel extends Model {

    /**
     * 获取启用的配送方式
     */
    public function get_list() {
        return $this->where(array('is_enable'=>1))->order('order_id asc,delivery_id asc')->select();
    }
    
    /**
     * 计算运费价格
     * @param int $delivery_id 配送方式
     * @param int $weight 重量单位（克）
     * @param int $address_id 用户地址ID
     */
    public function count_total_delivery($delivery_id,$weight,$address_id) {
        $model = $this->find($delivery_id);
        //异常情况
        //所选配送方式不存在
        if(empty($model)) {
           return -2;
        }
        //所选配送方式已禁用
        if($model['is_enable'] == 0) {
           return -1;
        }
        //如果是商品自提，不需要运费
        if($model['type'] == 3) {
            return 0;
        }
        $total_delivery = 0; //总运费
        $first_weight = $model['first_weight']; //首重计算单位
        $second_weight = $model['second_weight']; //续重计算单位
        //如果是 先付款后发货 或者 货到付款
        if($model['price_type'] == 1) { //统一地区运费
            $first_price = $model['first_price'];
            $second_price = $model['second_price'];
            if($weight <= $first_weight) { //如果低于首重
               $total_delivery = $first_price;
            } else {
               $total_delivery = $first_price + $second_price*($weight - $first_weight)/$second_weight;//如果高于首重 
            } 
        } else { //指定地区费用
            //获得用户收货地址
            $MemberAddressObj = new \Phone\Model\MemberAddressModel();
            $member_id = session('member_id');
            $address = $MemberAddressObj->get_address($member_id,$address_id);
            //获得配送方式指定地区
            $province = $address['province'];
            $city = $address['city'];
            $DeliveryAreaObj = M('ConfigDeliveryArea');
            $model2 = $DeliveryAreaObj->where(array('delivery_id'=>$delivery_id,'province'=>$province,'is_enable'=>1,'city'=>array(array('eq',$city),array('eq','所有城市'),'OR')))->find();
            if(!empty($model2)) {
                //已指定省份城市地区
                $first_price = $model2['first_price'];
                $second_price = $model2['second_price'];
            } else {
                //未指定省份城市地区
                if($model['open_default'] == 1) { //启用默认运费
                    $first_price = $model['first_price'];
                    $second_price = $model['second_price'];
                } else {
                    return -3;//不支持所配送城市
                }
            }
        }
        
        if($weight <= $first_weight) { //如果低于首重
           $total_delivery = $first_price;
        } else {
           $total_delivery = $first_price + $second_price*($weight - $first_weight)/$second_weight;//如果高于首重 
        } 
        return $total_delivery;
    }

}
